package com.example.app2;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.app2.util.FileUtil;

import java.io.File;

public class BitmapActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView bitmap;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bitmap);
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_load).setOnClickListener(this);
        bitmap = findViewById(R.id.iv_bitmap);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_save:
                String filename=System.currentTimeMillis()+".jpeg";
                //获取当前存储卡的私有目录
                String directory = getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).toString();
                path = directory+ File.separatorChar+filename;
                //从指定的资源文件中读取位图对象
                Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.mikasa);
                //将位图对象保存为图片文件
                FileUtil.saveImage(path,b1);
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
                break;
            case R.id.btn_load:
//                方法一：用以上方法获得bitmap并设置位图对象
//                bitmap.setImageBitmap(FileUtil.loadImage(path));
//                方法二：直接解析路径得到位图然后设置
//                bitmap.setImageBitmap(BitmapFactory.decodeFile(path));
//                方法三：直接设置路径
                bitmap.setImageURI(Uri.parse(path));
                break;
        }
    }
}